<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-top: 8px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        新增
      </el-button>
      <excelout></excelout>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <!-- <el-table-column label="ID" prop="id" align="center">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="年份" align="center">
        <template slot-scope="{row}">
          <span>{{ row.year }}</span>
        </template>
      </el-table-column>
      <el-table-column label="月份" align="center">
        <template slot-scope="{row}">
          <span>{{ row.month }}</span>
        </template>
      </el-table-column>
      <el-table-column label="成本" align="center">
        <template slot-scope="{row}">
          <span>{{ row.total_money }}</span>
        </template>
      </el-table-column>
      <el-table-column label="坏账" align="center">
        <template slot-scope="{row}">
          <span>{{ row.baddebt }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" class-name="status-col">
        <template slot-scope="{row}">
          {{ row.create_time|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" class-name="status-col">
        <template slot-scope="{row}">
          {{ row.update_time|formatDate }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>

          <el-button size="mini" type="danger" @click="deleteOperation(row.id)">
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :visible.sync="dialogFormVisible" :title="textMap[dialogStatus]">

      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 80%; margin-left:70px;"
      >
        <el-form-item label="年份" prop="year">
          <el-select v-model="temp.year" placeholder="请选择年份">
            <el-option v-for="(year,index) in this.year_list" :label="year" :value="year" />
          </el-select>
        </el-form-item>
        <el-form-item label="月份" prop="month">
          <el-select v-model="temp.month" placeholder="请选择月份">
            <el-option v-for="(month,index) in this.month_list" :label="month" :value="month" />

          </el-select>
        </el-form-item>
        <el-form-item label="成本" prop="total_money">
          <el-input v-model="temp.total_money" type="number" placeholder="请输入本月成本" />
        </el-form-item>
        <el-form-item label="坏账" prop="baddebt">
          <el-input v-model="temp.baddebt" type="number" placeholder="请输入本月坏账" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          Cancel
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          Confirm
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
var check_total_money = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value <= 0) {
    callback(new Error('必须大于0!'))
  } else {
    callback()
  }
}
import excelout from '@/components/excelout/index.vue'
import {
  create,
  update,
  deleteRecord,
  getAllList,
  costExcelout
} from '@/api/cost'
import {
  formatDate
} from '@/utils/formatDate.js'
import waves from '@/directive/waves' // waves directive
import {
  parseTime
} from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
export default {
  name: 'BalanceTable',
  components: {
    Pagination,excelout
  },
  directives: {
    waves
  },
  filters: {
    formatDate(time) {
      time = time * 1000
      const date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    }
  },
  data() {
    return {
      tableKey: 0,
      tableRecord: 1,
      list: [],
      total: 0,
      listLoading: true,
      dialogStatus: '',
      dialogFormVisible: false,
      listQuery: {
        page: 1,
        limit: 20
      },
      temp: {
        year: null,
        month: null,
        total_money: null,
        baddebt: null
      },
      month_list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12],
      year_list: [],
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        year: [{
          required: true,
          message: '年份必须选择',
          trigger: 'change'
        }],
        month: [{
          required: true,
          message: '月份必须选择',
          trigger: 'change'
        }],
        total_money: [{
          required: true,
          message: '余额必须输入',
          trigger: 'blur'
        },
        {
          required: true,
          message: '必须大于0',
          validator: check_total_money,
          trigger: 'blur'
        }
        ]
      }
    }
  },
  created() {
    const dt = new Date()
    this.year_list.push(dt.getFullYear() - 3)
    this.year_list.push(dt.getFullYear() - 2)
    this.year_list.push(dt.getFullYear() - 1)
    this.year_list.push(dt.getFullYear())
    this.year_list.push(dt.getFullYear() + 1)

    this.listLoading = false
    this.getList()
  },
  methods: {
    deleteOperation(id) {
      deleteRecord({ id: id }).then(res => {
        this.$notify({
          title: 'Success',
          message: 'Created Successfully',
          type: 'success',
          duration: 2000,
          onClose: this.getList()
        })
      })
    },
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          create(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000,
              onClose: this.getList()
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)

          update(tempData).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000,
              onClose: this.getList()
            })
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      getAllList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.0 * 1000)
      })
    },
    excelout() {
        this.listLoading = true
        this.listQuery.limit = this.total;
        costExcelout(this.listQuery).then(response => {
          this.listLoading = false
          const filepath = response.data.path
          window.location.href = filepath
        })
      },
  }
}
</script>

<style>
</style>
